package exercises.leetcode;

import exercises.newcoder.util.ListNode;

import java.util.ArrayDeque;

/**
 * <a href="">
 * </a>
 *
 * <p><span color="#87CEEB">描述:</span>
 *
 * @author or2
 * @date 2021年11月14日 时间: 10:49
 */
public class No5927 {
    public ListNode reverseEvenLengthGroups(ListNode head) {
        int k = 1, group = k;
        boolean odd = true;
        int totalLen = 0;
        for (ListNode p = head; p != null; p = p.next) totalLen++;

        for (ListNode p = head; p != null; p = p.next) {
            if (group == 0) {
                totalLen -= k;
                group = ++k;
                odd = !odd;
                if (totalLen < k) {
                    if (totalLen % 2 == 0) reverse(p, k);
                } else if (!odd) reverse(p, k);
            }
            group--;
        }

        return head;
    }

    private void reverse(ListNode p, int k) {
        var stack = new ArrayDeque<Integer>(k);
        int cnt = k;
        for (ListNode pp = p; pp != null && cnt > 0; pp = pp.next, cnt--) stack.push(pp.val);
        cnt = k;
        for (ListNode pp = p; pp != null && cnt > 0; pp = pp.next, cnt--) pp.val = stack.pop();
    }
}
